package com.example.simpletodolist;
import android.annotation.SuppressLint;
import android.app.Service;
import java.text.ParseException;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.widget.Toast;

/*
 * The alarm activity calls this class to start the alarm service.
 */
@SuppressLint("HandlerLeak")
public class AlarmService extends Service {
	private static final String TAG = "Alarm Service";
	private static final String START = "Start Alarm";
//	private static final String CANCEL = "Cancel";
	public static final String NOTIFY_INTENT = "NotifyIntent";
	private Looper mServiceLooper;
	//private static ServiceHandler mServiceHandler;
	private ServiceHandler mServiceHandler;
	// Handler that actually does the work in the Service
	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
			Bundle b = msg.getData();
			Intent receiver	= new Intent(getService(),AlarmReceiver.class);
			
			String time=b.getString(ToDoListDatabase.COL_TIME);
			String date=b.getString(ToDoListDatabase.COL_DATE);
			long rowId=b.getLong(ToDoListDatabase.KEY_ROWID);
			receiver.putExtras(b);
			try {
				Calendar calendar = DateTimeParser.parse(
						ToDoItemEdit.DatePickerFragments.DATE_FORMAT, 
						ToDoItemEdit.TimePickerFragments.TIME_FORMAT, 
						date, 
						time);
//				PendingIntent pendingAlarm = PendingIntent.getBroadcast(getService(), 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
				PendingIntent pendingAlarm = PendingIntent.getBroadcast(getService(), (int) rowId, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
				alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingAlarm);
				
			    Toast.makeText(getService(), START, Toast.LENGTH_LONG).show();
			    Log.d(TAG, START);
				//TODO temporary logs to see what value of ROWID is
				long tmpRowid = b.getLong(ToDoListDatabase.KEY_ROWID);
				String tmptitle = b.getString(ToDoListDatabase.COL_TITLE);
				String tmpbody = b.getString(ToDoListDatabase.COL_BODY);
				String tmptime = b.getString(ToDoListDatabase.COL_TIME);
				String tmpdate = b.getString(ToDoListDatabase.COL_DATE);
				tempLog1(tmpRowid, tmptitle, tmpbody, tmptime, tmpdate);
				///////////////////////////////////////////////////
			} catch (ParseException e) {
				Log.e("date/time", "Error Parsing date time.  Alarm not set.");
				e.printStackTrace();
			}
			
	        
			// Since the job is done, stop the service here. 
			stopSelf(msg.arg1);
		}

		private void tempLog1(long tmpRowid, String tmptitle, String tmpbody,
				String tmptime, String tmpdate) {
			Log.d("to service bundle",tmpRowid + " rowid");
			Log.d("to service bundle",tmptitle + " title");
			Log.d("to service bundle",tmpbody + " body");
			Log.d("to service bundle",tmpdate + " date");
			Log.d("to service bundle",tmptime + " time");
		}

	}
	
	@Override
	/*
	 * This is where our service would notify the user that
	 * the alarm deadline has expired on their to-do list.
	 */
	public int onStartCommand(Intent intent, int flags, int startid) {		
		Toast.makeText(this, "Alarm Service Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart"+intent.getExtras().getLong(ToDoListDatabase.KEY_ROWID));
		
		// For each start request, send a message to start a job and deliver
		// the start ID so we know which request we are stopping when done.
		Message msg = mServiceHandler.obtainMessage();
		msg.arg1 = startid;
		msg.setData(intent.getExtras()); // This is a really bad idea since I am 
		  								 // not checking if intent is not null
		mServiceHandler.sendMessage(msg);
		  
		// If we get killed, after returning from here, restart
		return START_STICKY;
		//player.start();
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onBind");
		return null;
	}
	
	@Override
	public void onCreate() {
		HandlerThread thread = new HandlerThread("ServiceStartArgs", 
				Process.THREAD_PRIORITY_BACKGROUND);
		thread.start();
		
		// Get the handler thread's looper and use it for our Handler
		mServiceLooper = thread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);
		Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Toast.makeText(this, "MyAlarmService.onDestroy", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
	}
	public Service getService()
	{
		return this;
	}
}
